import 'dart:io';
import 'package:cloud_medicine/components/above_loading.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/chat_api.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ChatCameraPage extends StatefulWidget {
  final File file;
  final int id;

  ChatCameraPage({Key key, @required this.file, @required this.id})
      : super(key: key);

  @override
  _ChatCameraPageState createState() => _ChatCameraPageState();
}

class _ChatCameraPageState extends State<ChatCameraPage> {
  File file;
  final picker = ImagePicker();
  final TextStyle style = TextStyle(color: Colors.white);

  // 照相获取图片
  Future getImageInCamera() async {
    final pickedFile = await picker.getImage(source: ImageSource.camera);
    Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => ChatCameraPage(
              file: File(pickedFile.path),
              id: widget.id,
            )));
  }

  @override
  void initState() {
    super.initState();
    file = widget.file;
  }

  _submit() async {
    showDialog(
        context: context,
        builder: (context) {
          return new AboveLoading(content: '加载中');
        });
    upLoadImage(file, (imgUrl) async {
      dynamic res = await addChat_api({
        "chat_id": widget.id,
        "content": imgUrl,
        "isFile": true,
      });
      if (res['code'] != 0) {
        errorToast(res['message']);
      } else {
        successToast('发送成功');
      }
      Navigator.pop(context);
      Navigator.pop(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        automaticallyImplyLeading: false,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            FlatButton(
              child: Text('重拍', style: style),
              onPressed: getImageInCamera,
            ),
            FlatButton(
              child: Text('发送', style: style),
              onPressed: _submit,
            )
          ],
        ),
      ),
      body: Center(
        child: Container(
          width: double.infinity,
          height: double.infinity / 3,
          child: Image.file(file),
        ),
      ),
    );
  }
}
